from math import *
import numpy as np
def count(X):
    """
    返回字典：元素类型及各个元素个数
    返回int：不同元素的总个数
    :param X:
    :return:
    """
    result={}
    number=0
    for i in range(np.shape(X)[0]):
        if X[i,0] in result.keys():
            result[X[i,0]]=result[X[i,0]]+1
        else:
            result[X[i,0]]=1
            number=number+1
    return result,number
def count_n(X,i,Y,n):
    """
    统计Y=n中X=i的出现频率(不用lagrange)
    :param X:
    :param i:
    :param Y:
    :param n:
    :return:
    """
    num=0
    for j in range(np.shape(Y)[0]):
        if Y[j,0]==n:
            if X[j,0]==i:
                num=num+1
    return num/count(Y)[0][n]
def count_n_lag(X,i,Y,n):
    """
    统计Y=n中X=i的出现频率(用lagrange)
    :param X:
    :param i:
    :param Y:
    :param n:
    :return:
    """
    num=0
    for j in range(np.shape(Y)[0]):
        if Y[j,0]==n:
            if X[j,0]==i:
                num=num+1
    return (num+1)/(count(Y)[0][n]+count(X)[-1])
def calc_miusigma(X,y,n):
    """
    返回y=n的连续值X序列的均值及方差
    返回：样本均值
    返回：样本方差
    :param X:
    :return:
    """
    sumtemp=0
    count=0
    miusigma={}
    for i in range(np.shape(y)[0]):
        if y[i,0]==n:
            sumtemp=sumtemp+X[i,0]
            count=count+1
    miu=sumtemp/count
    miusigma['miu']=miu
    sumtemp=0
    for i in range(np.shape(y)[0]):
        if y[i,0]==n:
            sumtemp=sumtemp+(X[i,0]-miu)**2
    sigma=sqrt(sumtemp/(count-1))
    miusigma['sigma']=sigma
    return miusigma
def calczt(x,X,Y,n):
    miusigma=calc_miusigma(X,Y,n)
    miu=miusigma['miu']
    sigma=miusigma['sigma']
    p=pow(sqrt(2*pi)*sigma,-1)*exp(-(x-miu)**2/(2*sigma**2))
    return p
def Bayes(X,Y):
    yn=count(Y)
    n=np.shape(X)[-1]
    xtest=[]
    xtest_ls={0:1,1:1,2:1,3:1,4:1,5:1}
    xtest_lx={6:0.697,7:0.460}
    ypresult={}
    for j in yn[0].keys():
        PI = (yn[0][j])/(np.shape(Y)[0])
        for i in xtest_ls.keys():   #第i列
            temp=X[:,i]
            value=xtest_ls[i]
            p=count_n(temp,value,Y,j)
            PI=PI*p
        ypresult[j]=PI
    for j in yn[0].keys():
        PI=ypresult[j]
        for i in xtest_lx.keys():
            temp=X[:,i]
            p=calczt(xtest_lx[i],temp,Y,j)
            PI=PI*p
        ypresult[j]=PI
    return ypresult
data=np.loadtxt('data.csv',dtype=None,delimiter=',')
X=np.mat(data[:,0:-1])
Y=np.mat(data[:,-1]).reshape(np.shape(data)[0],1)
print(Bayes(X,Y))